package com.liy.framework.web.spring.controller;

import com.liy.framework.common.annotation.MethodPermission;
import com.liy.framework.common.extvo.ResultVO;
import com.liy.framework.common.utils.Tools;
import com.liy.framework.common.vo.SupportVO;
import com.liy.framework.web.spring.service.IBaseService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import javax.validation.Valid;

@Validated
public class BaseCrudController< Biz extends IBaseService, Entity extends SupportVO<String>   >      extends BaseController
{
    protected static Logger log;

    @Autowired
    protected Biz baseService;

    @RequestMapping(value = { "/add" }, method = { RequestMethod.POST })
    @ResponseBody
    @MethodPermission(codes = { "INSERT" }, description = "")
    public ResultVO add(@RequestBody @Valid Entity entity) {
        try {
            if (Tools.StringIsNullOrSpace(entity.getId())) {
                entity.setId(Tools.getNewUUID());
            }
            this.baseService.add(entity);
            return new ResultVO(true, "", "200", entity);
        }
        catch (Exception e) {
            BaseCrudController.log.error(e.getMessage(), e);
            return new ResultVO(false, " : " + e.getMessage(), "500");
        }
    }



    @RequestMapping(value = { "/update" }, method = { RequestMethod.PUT })
    @ResponseBody
    @MethodPermission(codes = { "UPDATE" }, description = "")
    public ResultVO update(@RequestBody final Entity entity) {
        try {
            if (Tools.StringIsNullOrSpace(entity.getId())) {
                return new ResultVO(false, "");
            }
            if (this.baseService.findById(entity.getId()) == null) {
                return new ResultVO(false, "");
            }
            this.baseService.update(entity);
            return new ResultVO(true, "", "200",entity);
        }
        catch (Exception e) {
            BaseCrudController.log.error(e.getMessage(),e);
            return new ResultVO(false, "" + e.getMessage(), "500");
        }
    }



    @RequestMapping(value = { "/del/{id}" }, method = { RequestMethod.DELETE })
    @ResponseBody
    @MethodPermission(codes = { "DELETE" }, description = "")
    public ResultVO delete(@PathVariable final String id) {
        try {
            final Entity entity = (Entity) this.baseService.findById(id);
            if (entity == null) {
                return new ResultVO(false, "");
            }
            this.baseService.delete(id);
            return new ResultVO(true, "");
        }
        catch (Exception e) {
            BaseCrudController.log.error(e.getMessage(),e);
            return new ResultVO(true, "" + e.getMessage(), "500");
        }
    }

    static {
        BaseCrudController.log = LoggerFactory.getLogger(BaseCrudController.class);
    }
}
